package com.itheima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.search.document.ArticleInfoDocument;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.service.ArticleInfoSearchService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArticleInfoSearchServiceImpl implements ArticleInfoSearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**
     * app端文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public List<ArticleInfoDocument> search(SearchDto dto) {
        //参数校验
        if (null == dto) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }

        //时间处理
        if (null == dto.getMinBehotTime()) {
            dto.setMinBehotTime(new Date());
        }

        //构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        boolQuery.must(QueryBuilders.termQuery("isDown", 0))
                .must(QueryBuilders.termQuery("isDelete", 0));
        if (StringUtils.isNotEmpty(dto.getTag()) && !"__all__".equals(dto.getTag())) {
            boolQuery.must(QueryBuilders.termQuery("channelId", Integer.parseInt(dto.getTag())));
        }

        if (StringUtils.isNotEmpty(dto.getSearchWords())) {
            //有搜索内容
            boolQuery.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        }
        queryBuilder.withQuery(boolQuery);

        //分页设置-排序
        queryBuilder.withSort(SortBuilders.fieldSort("publishTime").order(SortOrder.DESC));
        //高亮
        queryBuilder.withHighlightFields(new HighlightBuilder.Field("title"));
        queryBuilder.withHighlightBuilder(new HighlightBuilder().preTags("<font color='red'>")
                .postTags("</font>").requireFieldMatch(false));

        NativeSearchQuery query = queryBuilder.build();

        //5、查询
        SearchHits<ArticleInfoDocument> searchResult = elasticsearchRestTemplate.search(query, ArticleInfoDocument.class);

        //6、解析结果
        List<SearchHit<ArticleInfoDocument>> searchHits = searchResult.getSearchHits();
        List<ArticleInfoDocument> list = new ArrayList<>();

        for (SearchHit<ArticleInfoDocument> searchHit : searchHits) {
            ArticleInfoDocument articleInfoDocument = searchHit.getContent();
            //解析高亮
            List<String> highlights = searchHit.getHighlightField("title");
            if(!CollectionUtils.isEmpty(highlights)){
                //有高亮
                //多个以逗号分割
                String title = String.join(",", highlights);
                articleInfoDocument.setTitle(title);
            }
            list.add(articleInfoDocument);
        }
        //返回数据
        return list;
    }
}
